package com.zebra.remoting.protocol;

import com.zebra.remoting.util.RemotingUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;


public class ZebraEncoder extends MessageToByteEncoder<ZebraCommand> {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(ZebraEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, ZebraCommand response, ByteBuf out) throws Exception{
        try {
            ByteBuf msgBuf = PooledByteBufAllocator.DEFAULT.directBuffer();
            response.getResponse().write(msgBuf);
            int length = msgBuf.readableBytes() + 28;  //int length = msgBuf.readableBytes() + 2;

            out.writeShort((short)(response.getCmd()^length^1616));
            out.writeShort(length);

            out.writeShort(response.getCmd());  // cmd
            out.writeLong(response.getToken());  // token
            out.writeLong(response.getUserId());  // userId
            out.writeShort(response.getState());    //state
            out.writeShort(response.getGameId());     //gameId
            out.writeInt(response.getId());   // id
            out.writeShort(response.getReserve());     //reserve
            out.writeBytes(msgBuf);
            msgBuf.release();

            if (!response.isLogs() && logger.isInfoEnabled()){
                logger.info("Response c:{} u:{} g:{} s:{} l:{} ; {}",
                        response.getCmd(), response.getUserId(), response.getGameId(), response.getState(), length, RemotingUtil.channelToString(ctx.channel()));
            }

        }catch (Exception e){
            logger.error("Response Error c:{}   {} {} ", response.getCmd(),   RemotingUtil.channelToString(ctx.channel()), response.toString());
            logger.error("Response Encoder", e);
            throw  e;
        }
    }


}
